import datetime, time
from exportXls import exportCard
from personInfo import personIdInfo, demoPerson, furuqiPerson, jiediaoPerson
import os

def genPersonId():
    dictPPID = {}
    for item in personIdInfo:
        dictPPID[personIdInfo[item][0]] = item

    return dictPPID

def readKQ():
    # print(genPersonId())
    dictPPID = genPersonId() #通过名字反查编号

    lstId = []
    dictDate = {}
    tmpdict = {}

    lstDataFiles = [] #所有data文件列表
    # dataDir = r"E:\办公室文档\考勤——\201706"
    dataDir = r"E:\办公室文档\考勤——\201707"
    for idir in os.listdir(dataDir):
        if os.path.isfile(dataDir + os.path.sep + idir):
            # if os.path.splitext(idir)[1] == '.dat':    # 分割文件名和文件扩展名，并且扩展名为'dat'
            # if os.path.splitext(idir)[1] == '.txt':    # 分割文件名和文件扩展名，并且扩展名为'dat'
            if os.path.splitext(idir)[1] == '.txt' or os.path.splitext(idir)[1] == '.dat':    # 分割文件名和文件扩展名，并且扩展名为'dat'
                # print(idir)
                tmpFile = dataDir + os.path.sep + idir
                lstDataFiles.append(tmpFile)

    # print("@"*20, lstDataFiles[0])
    # path = r"E:\办公室文档\考勤——\201706\3694171900137_attlog.dat"
    
    for ifile in lstDataFiles:
        fobj = open(ifile, 'r')
        for eachline in fobj:
            # print(eachline, end="")
            tmpInfo = eachline.split("\t")
            # print(tmpInfo[4], dictPPID[tmpInfo[4]], len(tmpInfo))
            # print(tmpInfo[4],  len(tmpInfo))
            if len(tmpInfo) == 8: #只有名字，特校 txt文件
                # if tmpInfo[4] == "黄奕琦": #特校借调至机关
                if tmpInfo[4] in jiediaoPerson.values():
                    continue;
                # print(tmpInfo, tmpInfo[4] in dictPPID.keys())
                if tmpInfo[4] in dictPPID.keys():
                    curId = dictPPID[tmpInfo[4]]
            else: #有编号 dat文件。
                curId = tmpInfo[0].strip()
            if len(curId) < 3:
                continue;
            tmpTime = time.strptime(tmpInfo[1], "%Y-%m-%d %X")
            curDateTime = datetime.datetime(*tmpTime[:6])
            curDate = curDateTime.date()
            curTime = curDateTime.time()
            
            if curId not in lstId:
                lstId.append(curId)
                dictDate[curId] = {}

            # print(dictDate)
            if curDate not in dictDate[curId].keys():            
                # tmpdict[curDate] = [curTime,] 
                dictDate[curId][curDate]=[curTime,]
                # print(dictDate, 2)
            else:
                # print(dictDate[curId][curDate], type(dictDate[curId][curDate]), curTime)            
                dictDate[curId][curDate].append(curTime)

            # if curId == "2004":
            #     print(curId, curDate, curTime)
        fobj.close()        
        print('--'*20, ifile)

    # printOneId('1004', dictDate)
    # print("######################")

    # return
    # print(dictDate.keys(), len(dictDate.keys()), dictDate['1004'])

    lstId.sort()

    lstNoCardAllDay = []    #全天缺勤人数
    lstNoCardMorning = []   #上午缺勤人数
    lstNoCarAfternoot = []  #下午缺勤人数
    lstChiDao = []          #迟到人数
    lstZaoTui = []          #早退人数
    lstZaoYiChang = []
    lstWanYiChang = []

    setYear = 2017
    setMonth =7
    setDayStart = 1
    setDayEnd = 31
    lstAllDate = [datetime.date(setYear,setMonth,i) for i in range(setDayStart,setDayEnd+1)]
    lstAllDate2 = lstAllDate.copy()
    for idate in lstAllDate2:  #删除周末两天
        # print(idate, "===========")
        if idate.isoweekday() == 6 or idate.isoweekday() == 7:
            lstAllDate.remove(idate)

    # print(lstAllDate)
    recordPersonInfo = {}
    flagTxt = ["提前", "早卡", "迟到", "早退", "晚卡", "更晚"]
   

    for ikey1 in lstId:
        recordPersonInfo[ikey1] = {} #对每个人记录6个时间点
        # print(ikey1, end="\t") #打印编号
        lstTmpDate = [item for item in dictDate[ikey1].keys()] #按日期排序
        lstTmpDate.sort()
        for ikey2 in lstAllDate:
            if ikey2 not in recordPersonInfo.keys():
                recordPersonInfo[ikey1][ikey2] = {flagTxt[0]:"0", flagTxt[1]:"0", flagTxt[2]:"0", flagTxt[3]:"0", flagTxt[4]:"0", flagTxt[5]:"0"}

            if ikey2 not in lstTmpDate: #当前人员的考勤记录中没有某一工作日
                continue;

            lstTmpTime = dictDate[ikey1][ikey2]  #取出该id该天所有的打卡时间进行排序
            lstTmpTime.sort()

            for itime in lstTmpTime:
                if itime < datetime.time(7,20,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[0]] = itime.isoformat()  #只记录一个时间即可
                if itime >= datetime.time(7,20,0) and itime < datetime.time(8,31,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[1]] = itime.isoformat()  #正常早上打卡
                if itime >= datetime.time(8,31,0) and itime <= datetime.time(9,0,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[2]] = itime.isoformat()  #迟到
                if itime > datetime.time(17,0,0) and itime < datetime.time(17,30,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[3]] = itime.isoformat()  #早退
                if itime >= datetime.time(17,30,0) and itime <= datetime.time(20,0,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[4]] = itime.isoformat()  #正常下午打卡
                if itime > datetime.time(20,0,0) :
                    recordPersonInfo[ikey1][ikey2][flagTxt[5]] = itime.isoformat()  #更晚打卡

    #=====================================
    #1、允许早下班30分钟人员修订其记录
    #=====================================
    demoPPId = [item for item in demoPerson.keys()] #按日期排序
    # print(demoPPId)
    for ikey1 in demoPPId:
        # recordPersonInfo[ikey1] = {} #对每个人记录6个时间点
        # print(ikey1, demoPPId[ikey1], end="\t") #打印编号
        # print(ikey1, ikey1 in dictDate.keys())
        if ikey1 in dictDate.keys():
            lstTmpDate = [item for item in dictDate[ikey1].keys()] #按日期排序
        else:
            continue;

        lstTmpDate.sort()
        for ikey2 in lstAllDate:
            #只是修订其所有日期，不再新增记录
            # if ikey2 not in recordPersonInfo.keys():
            #     recordPersonInfo[ikey1][ikey2] = {flagTxt[0]:"0", flagTxt[1]:"0", flagTxt[2]:"0", flagTxt[3]:"0", flagTxt[4]:"0", flagTxt[5]:"0"}

            if ikey2 not in lstTmpDate: #当前人员的考勤记录中没有某一工作日
                continue;

            lstTmpTime = dictDate[ikey1][ikey2]  #取出该id该天所有的打卡时间进行排序
            lstTmpTime.sort()

            for itime in lstTmpTime:
                if itime < datetime.time(7,50,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[0]] = itime.isoformat()  #只记录一个时间即可
                if itime >= datetime.time(7,50,0) and itime < datetime.time(8,31,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[1]] = itime.isoformat()  #正常早上打卡
                if itime >= datetime.time(8,31,0) and itime <= datetime.time(9,0,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[2]] = itime.isoformat()  #迟到
                if itime > datetime.time(16,30,0) and itime < datetime.time(17,0,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[3]] = itime.isoformat()  #早退
                if itime >= datetime.time(17,0,0) and itime <= datetime.time(20,0,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[4]] = itime.isoformat()  #正常下午打卡
                if itime > datetime.time(20,0,0) :
                    recordPersonInfo[ikey1][ikey2][flagTxt[5]] = itime.isoformat()  #更晚打卡

    
    #=====================================
    #2、允许早下班1小时人员修订其记录
    #=====================================
    demoPPId = [item for item in furuqiPerson.keys()] #按日期排序
    # print(demoPPId)
    for ikey1 in demoPPId:
        # recordPersonInfo[ikey1] = {} #对每个人记录6个时间点
        # print(ikey1, end="\t") #打印编号
        if ikey1 in dictDate.keys():
            lstTmpDate = [item for item in dictDate[ikey1].keys()] #按日期排序
        else:
            continue;
        lstTmpDate = [item for item in dictDate[ikey1].keys()] #按日期排序
        lstTmpDate.sort()
        for ikey2 in lstAllDate:
            #只是修订其所有日期，不再新增记录
            # if ikey2 not in recordPersonInfo.keys():
            #     recordPersonInfo[ikey1][ikey2] = {flagTxt[0]:"0", flagTxt[1]:"0", flagTxt[2]:"0", flagTxt[3]:"0", flagTxt[4]:"0", flagTxt[5]:"0"}

            if ikey2 not in lstTmpDate: #当前人员的考勤记录中没有某一工作日
                continue;

            lstTmpTime = dictDate[ikey1][ikey2]  #取出该id该天所有的打卡时间进行排序
            lstTmpTime.sort()

            for itime in lstTmpTime:
                if itime < datetime.time(7,50,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[0]] = itime.isoformat()  #只记录一个时间即可
                if itime >= datetime.time(7,50,0) and itime < datetime.time(8,31,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[1]] = itime.isoformat()  #正常早上打卡
                if itime >= datetime.time(8,31,0) and itime <= datetime.time(9,0,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[2]] = itime.isoformat()  #迟到
                if itime > datetime.time(16,0,0) and itime < datetime.time(16,30,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[3]] = itime.isoformat()  #早退
                if itime >= datetime.time(16,30,0) and itime <= datetime.time(20,0,0):
                    recordPersonInfo[ikey1][ikey2][flagTxt[4]] = itime.isoformat()  #正常下午打卡
                if itime > datetime.time(20,0,0) :
                    recordPersonInfo[ikey1][ikey2][flagTxt[5]] = itime.isoformat()  #更晚打卡

    #=====================================

    #统计
    dictDispResult = {"1":"本日无有效打卡记录", "2":"上午无打卡", "3":"下午无打卡", "4":"迟到", "5":"早退", "6":"早异常", "7":"晚异常"}
    lstResultPrint = {}
    for ikey1 in lstId:
        lstTmpDate = [item for item in recordPersonInfo[ikey1].keys()] #按日期排序
        lstTmpDate.sort()
        lstResultPrint[ikey1] = {}
        # print()
        # print(ikey1, ":")
        for ikey2 in lstTmpDate:
            if ikey2 not in lstResultPrint[ikey1].keys():
                lstResultPrint[ikey1][ikey2] = [["*", "*", "*"],]

            curinfo = recordPersonInfo[ikey1][ikey2]            
            # print(ikey2.isoformat(), end=",")            

            if curinfo[flagTxt[1]] == "0" and curinfo[flagTxt[2]] == "0" and curinfo[flagTxt[3]] == "0" and curinfo[flagTxt[4]] == "0":
                lstNoCardAllDay.append([ikey1, ikey2.isoformat()])
                lstResultPrint[ikey1][ikey2].append(["1", "0"])
                lstResultPrint[ikey1][ikey2][0][0] = "2"      #设置未打卡标志
                lstResultPrint[ikey1][ikey2][0][1] = "3"      #设置未打卡标志
            elif curinfo[flagTxt[1]] == "0" and curinfo[flagTxt[2]] == "0":
                lstNoCardMorning.append([ikey1, ikey2.isoformat()])
                lstResultPrint[ikey1][ikey2].append(["2", "0"])
                lstResultPrint[ikey1][ikey2][0][0] = "2"      #设置未打卡标志
            elif curinfo[flagTxt[3]] == "0" and curinfo[flagTxt[4]] == "0":
                lstNoCarAfternoot.append([ikey1, ikey2.isoformat()])
                lstResultPrint[ikey1][ikey2].append(["3", "0"])
                lstResultPrint[ikey1][ikey2][0][1] = "3"      #设置未打卡标志
            
            if curinfo[flagTxt[1]] == "0" and curinfo[flagTxt[2]] != "0": #迟到
                lstChiDao.append([ikey1, ikey2.isoformat(), curinfo[flagTxt[2]]])
                lstResultPrint[ikey1][ikey2].append(["4", curinfo[flagTxt[2]]])
                lstResultPrint[ikey1][ikey2][0][0] = "4"      #设置未打卡标志
            if curinfo[flagTxt[4]] == "0" and curinfo[flagTxt[3]] != "0": #早退
                lstZaoTui.append([ikey1, ikey2.isoformat(), curinfo[flagTxt[3]]])
                lstResultPrint[ikey1][ikey2].append(["5", curinfo[flagTxt[3]]])
                lstResultPrint[ikey1][ikey2][0][1] = "5"      #设置未打卡标志

            if curinfo[flagTxt[0]] != "0" and curinfo[flagTxt[1]] == "0" : #早异常
                lstZaoYiChang.append([ikey1, ikey2.isoformat(), curinfo[flagTxt[0]]])
                lstResultPrint[ikey1][ikey2].append(["6", curinfo[flagTxt[0]]])
                lstResultPrint[ikey1][ikey2][0][2] = "6"      #设置未打卡标志
            if curinfo[flagTxt[5]] != "0" and curinfo[flagTxt[4]] == "0" : #晚异常
                lstWanYiChang.append([ikey1, ikey2.isoformat(), curinfo[flagTxt[5]]])
                lstResultPrint[ikey1][ikey2].append(["7", curinfo[flagTxt[5]]])
                lstResultPrint[ikey1][ikey2][0][2] = "7"      #设置未打卡标志

    exportCard(lstResultPrint)

    # print("============================")
    # print(lstResultPrint['1011'])
    # print("============================")
    
    # for ikey1 in lstResultPrint:
    # for ikey1 in lstId:
    #     print(personIdInfo[ikey1], end=":") 
    #     tmpdatelst = [item for item in lstResultPrint[ikey1].keys()] #按日期排序
    #     tmpdatelst.sort()
    #     for ikey2 in tmpdatelst:
    #         if len(lstResultPrint[ikey1][ikey2]) == 0:
    #             print(ikey2, "正常", end=",")
    #         else:
    #             print(ikey2, end=" ")
    #             for item in lstResultPrint[ikey1][ikey2]:
    #                 if item[1] == "0":
    #                     dispRe = " "
    #                 else:
    #                     dispRe = item[1]
    #                 print(dictDispResult[item[0]], dispRe, end=", ")
    #     print()

    #         # print(type(ikey2))
    #         if ikey2 not in lstTmpDate: #当前人员的考勤记录中没有某一工作日
    #             # print("="*8,ikey2, ikey1)
    #             lstNoCardAllDay.append([ikey1, ikey2.isoformat()]) #记录该天未打卡
    #             continue

    #         # if len(lstTmpTime) == 0:
    #         #     lstNoCardAllDay.append[ikey1, ikey2.isoformat()]
    #         if len(lstTmpTime) == 1:  #只有一次记录
    #             if lstTmpTime[0] <= datetime.time(12,0,0): #上午
    #                 tmpMorning = lstTmpTime[0]
    #                 tmpAfternoot = datetime.time(14,30,1) #设定下午未打卡
    #             else: #下午
    #                 tmpMorning = datetime.time(11,59,59)  #设定上午未打卡
    #                 tmpAfternoot = lstTmpTime[0]

    #         if len(lstTmpTime)>=2:
    #             if lstTmpTime[0] >= datetime.time(12,0,0): #上午未打卡
    #                 tmpMorning = datetime.time(11,59,59)  #设定上午未打卡
    #             elif lstTmpTime[-1] <= datetime.time(12,0,0)

    #             tmpMorning = lstTmpTime[0]
    #             tmpAfternoot = lstTmpTime[-1]
    #             if tmpAfternoot < datetime.time(12,0,0):
    #                 tmpAfternoot = datetime.time(14,30,1)

    #         if tmpMorning <= datetime.time(9,0,0) and tmpMorning >= datetime.time(8,30,0):  #迟到
    #             lstChiDao.append([ikey1, ikey2.isoformat(), tmpMorning.isoformat()])
    #         elif tmpMorning <= datetime.time(12,0,0) and tmpMorning >= datetime.time(9,0,0):  #9点以后上班，上午缺勤
    #             lstNoCardMorning.append([ikey1, ikey2.isoformat()])
    #         elif tmpAfternoot <= datetime.time(17,30,0) and tmpAfternoot >= datetime.time(17,0,0): #早退
    #             lstZaoTui.append([ikey1, ikey2.isoformat(), tmpAfternoot.isoformat()])
    #         elif tmpAfternoot < datetime.time(17,0,0) and tmpAfternoot >= datetime.time(14,30,0): #17点以前打卡，下午缺勤                
    #             lstNoCarAfternoot.append([ikey1, ikey2.isoformat()])


    #         # print(ikey2, dictDate[ikey1][ikey2].sort(), end=",")
    #         # print(ikey2, end=",") #打印日期
    #         # print(dictDate[ikey1][ikey2], end=",")
    #     # print("~~~~~~~~~")

    # lstNoCardMorning2 = lstNoCardMorning.copy()
    # for inocard in lstNoCardMorning2:
    #     if inocard in lstNoCarAfternoot:
    #         lstNoCardAllDay.append(inocard)
    #         lstNoCarAfternoot.pop(inocard)
    #         lstNoCardMorning.pop(inocard)

    lstDispInfo = [["全天未打卡人数：", lstNoCardAllDay], 
        ["上午未打卡人数：", lstNoCardMorning], 
        ["下午未打卡人数：", lstNoCarAfternoot],
        ["迟到人数：", lstChiDao],
        ["早退人数：", lstZaoTui],
        ["早异常：", lstZaoYiChang],
        ["晚异常：", lstWanYiChang],
        ]

    # print("================ 结果统计 =======================")
    # for item in lstDispInfo:
    #     print(item[0])
    #     printLstId(item[1])
    print("================ 结果统计结束 =======================")
    
    
    # printOneId('1011', dictDate)

def printLstId(lstNocard):
    for item in lstNocard:
        for item2 in item:
            print(" "*4, item2, end=",")
        print()

def printOneId(printID, dictDate):
    # printID = "1004"
    print("\r\n=================  printOneId  ======================") 
    lstTmpDate = [item for item in dictDate[printID].keys()] #按日期排序
    lstTmpDate.sort()
    for idate in lstTmpDate:
        print(idate)
        lsttmptime = dictDate[printID][idate]
        [print(item, end=",") for item in lsttmptime]
        lsttmptime.sort() 
        print()
        # print(lsttmptime)       
        print(lsttmptime[0], lsttmptime[-1], end="~~")
        print("\r\n")
    print("=================  printOneId  End ======================")




if __name__ == "__main__":
    readKQ()